package com.dal;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;

import com.alibaba.fastjson.JSONObject;
import com.conf.OAConfig;
import com.db.DBConnection;

public class Common {
	public static void main(String[] args) {
		new Common().formPost();
	}
	public HashMap<String, String> initOA_Unit(){
		Connection conn=new DBConnection().getDefConn();
		Statement stmt=null;
		HashMap<String, String> map=new HashMap<String, String>();
		try {
			stmt=conn.createStatement();
			String sql="select id,code,name from org_unit where IS_DELETED=0 and IS_ENABLE=1 and IS_GROUP=0 and IS_INTERNAL=1";
			ResultSet ret=stmt.executeQuery(sql);
			while(ret.next()){
				map.put(ret.getString("code"),ret.getString("id"));
			}
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			return map;
		}finally {
			try {
				stmt.close();
				conn.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
	
	public HashMap<String, String> initOA_Member(){
		Connection conn=new DBConnection().getDefConn();
		Statement stmt=null;
		HashMap<String, String> map=new HashMap<String, String>();
		try {
			stmt=conn.createStatement();
			String sql="select m.id,m.code,p.LOGIN_NAME,m.org_department_id,m.org_account_id from org_member m,org_principal p where m.id=p.MEMBER_ID";
			ResultSet ret=stmt.executeQuery(sql);
			while(ret.next()){
				map.put(ret.getString("code"),ret.getString("id")+","+ret.getString("LOGIN_NAME")+","+ret.getString("org_department_id")+","+ret.getString("org_account_id"));
			}
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			return map;
		}finally {
			try {
				stmt.close();
				conn.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
	
	public HashMap<String, String> initEntity(){
		Connection conn=new DBConnection().getDefConn();
		Statement stmt=null;
		HashMap<String, String> map=new HashMap<String, String>();
		try {
			stmt=conn.createStatement();
			String sql="select field0014 实体,field0017 单位 from "+OAConfig.cg_Entitytable;
			ResultSet ret=stmt.executeQuery(sql);
			while(ret.next()){
				map.put(ret.getString("实体"),ret.getString("单位"));
			}
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			return map;
		}finally {
			try {
				stmt.close();
				conn.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
	
	public HashMap<String, String> initOA_WorkNo(){
		Connection conn=new DBConnection().getDefConn();
		Statement stmt=null;
		HashMap<String, String> map=new HashMap<String, String>();
		try {
			stmt=conn.createStatement();
			String sql="select field0007 id,isnull(field0014,'') 编码,i.showvalue 班次名称,isnull(field0015,'00:00') 开始," +
					"isnull(field0016,'00:00') 结束,field0017 结束跨天,field0018 开始跨天  from formmain_0575 f,ctp_enum_item i " +
					"where i.id=field0007 ";
			ResultSet ret=stmt.executeQuery(sql);
			while(ret.next()){
				map.put(ret.getString("班次名称"),ret.getString("id")+","+ret.getString("编码")+","+ret.getString("开始")+","+ret.getString("结束")+","+ret.getString("开始跨天")+","+ret.getString("结束跨天"));
			}
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			return map;
		}finally {
			try {
				stmt.close();
				conn.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
	
	public HashMap<String, String> initOA_WorkType(){
		Connection conn=new DBConnection().getDefConn();
		Statement stmt=null;
		HashMap<String, String> map=new HashMap<String, String>();
		try {
			stmt=conn.createStatement();
			String sql="select field0019,field0018 from formmain_0654 where field0019 is not null";
			ResultSet ret=stmt.executeQuery(sql);
			while(ret.next()){
				try {
					map.put(ret.getString(1).substring(0, 10),ret.getString(2));
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			return map;
		} catch (Exception e) {
			e.printStackTrace();
			return map;
		}finally {
			try {
				stmt.close();
				conn.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
	
	public String upload(String filePath){
		try {
			URL url = new URL("http://127.0.0.1:8999/seeyon/userToken.jsp");  
	        HttpURLConnection urlcon = (HttpURLConnection)url.openConnection();  
	        urlcon.connect();         //获取连接  
	        InputStream is_token = urlcon.getInputStream();  
	        BufferedReader buffer = new BufferedReader(new InputStreamReader(is_token));
	        StringBuffer bs = new StringBuffer();  
	        String l = null;  
	        while((l=buffer.readLine())!=null){  
	           bs.append(l);  
	        }  
	        is_token.close();
	        
			  URL preUrl = null;
		      URLConnection uc = null;
		      preUrl = new URL("http://127.0.0.1:8999/seeyon/uploadService.do?method=processUploadService"
			          +"&senderLoginName="+"yysjs"
			          +"&token="+bs.toString());
		      uc = preUrl.openConnection();
		      HttpURLConnection hc = (HttpURLConnection) uc;
		      hc.setDoInput(true);
		      hc.setDoOutput(true);
		      hc.setUseCaches(false);
		      hc.setRequestProperty("contentType", "charset=utf-8");
		      hc.setRequestMethod("POST");
		      File source=new File(filePath);
		      DataInputStream  input=new DataInputStream(new FileInputStream(source));
		      String BOUNDARY = "-----------------------------264141203718551"; // 分隔符
		      String fileName=source.getName();
		      StringBuffer sb = new StringBuffer();
		      sb.append("--");
		      sb.append(BOUNDARY);
		      sb.append("\r\n");
		      sb.append("Content-Disposition: form-data;name=\""+fileName+"\"; filename=\""+filePath+"\""+"\r\n");
		      sb.append("Content-Type:application/pdf"+"\r\n\r\n");
		      sb.append("\r\n");
		      
		      hc.setRequestProperty("Charset", "utf-8"); // 设置编码
		      hc.setRequestProperty("connection", "keep-alive");
		      hc.setRequestProperty("Content-Type", "multipart/form-data;boundary="
	                    + BOUNDARY);
	            
		      byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");
		      DataOutputStream dos = new DataOutputStream(hc.getOutputStream());
		      dos.write(sb.toString().getBytes("utf-8"));
		      int cc=0;
		      byte[] bufferOut=new byte[1024*1024];
		      while((cc=input.read(bufferOut))!=-1)
		      {
		          dos.write(bufferOut,0,cc);
		      }
		      input.close();
		      dos.write(end_data);
		      dos.flush();

		      InputStream is = hc.getInputStream();
              StringBuffer sb1 = new StringBuffer();
              int ss;
              while ((ss = is.read()) != -1) {
                  sb1.append((char) ss);
              }
              String result = sb1.toString();
              result = new String(result.getBytes("iso8859-1"), "utf-8");
              return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "";
		}
	}
	
	public void down(String fileid,String name){
		StringBuffer parameters = new StringBuffer();
		try {
			URL url = new URL("http://10.9.112.136/seeyon/userToken.jsp");  
	        HttpURLConnection urlcon = (HttpURLConnection)url.openConnection();  
	        urlcon.connect();         //获取连接  
	        InputStream is_token = urlcon.getInputStream();  
	        BufferedReader buffer = new BufferedReader(new InputStreamReader(is_token));
	        StringBuffer bs = new StringBuffer();  
	        String l = null;  
	        while((l=buffer.readLine())!=null){  
	           bs.append(l);  
	        }  
	        is_token.close();
	        
			 parameters.append("fileId="+fileid);
			 parameters.append("&token="+bs.toString()); 
			 URL preUrl = null; 
			 URLConnection uc = null;
			 preUrl = new URL("http://10.9.112.136/seeyon/services/downloadService");
		     String s = parameters.toString(); 
		     uc = preUrl.openConnection(); 
		     uc.setDoOutput(true); 
		     uc.setUseCaches(false); 
		     uc.setRequestProperty("Content-Type", 
		       "application/x-www-form-urlencoded");
		     HttpURLConnection hc = (HttpURLConnection) uc;
		     hc.setRequestMethod("POST");
		     OutputStream os = hc.getOutputStream();
		     DataOutputStream dos = new DataOutputStream(os); 
		     dos.writeBytes(s); 
		     dos.flush(); 
		     dos.close();
		     
		     InputStream is = hc.getInputStream();
		     byte[] temp = new byte[is.available()];
		     byte[] result = new byte[0];
		     int size = 0;
		     if(temp.length>0){
				while ((size = is.read(temp)) != -1) {
					byte[] readBytes = new byte[size];
					System.arraycopy(temp, 0, readBytes, 0, size);
					result = mergeArray(new byte[][] { result, readBytes });
				}
		     }
			
		     /* 生成实体文件 */
			 FileOutputStream file = new FileOutputStream("D:/" + name);
			 file.write(result);
			
			 int index = 1;
			 int ch;
			 while ((ch = is.read()) != -1)
			 {
				 file.write(ch);
				 index++;
			 }
			 file.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public byte[] mergeArray(byte[]... a) {  
        // 合并完之后数组的总长度  
        int index = 0;  
        int sum = 0;  
        for (int i = 0; i < a.length; i++) {  
            sum = sum + a[i].length;  
        }  
        byte[] result = new byte[sum];  
        for (int i = 0; i < a.length; i++) {  
            int lengthOne = a[i].length;  
            if(lengthOne==0){  
                continue;  
            }  
            // 拷贝数组  
            System.arraycopy(a[i], 0, result, index, lengthOne);  
            index = index + lengthOne;  
        }  
        return result;  
    }
	
	public String formPost(){
		try{
			JSONObject json=new JSONObject();
			json.put("key", "中文测试");
			json.put("value", "乱码");
			HttpClient client = new HttpClient();
			PostMethod method = new PostMethod("http://116.63.70.228:8085/third/oa_service.jsp?method=startCG");
			method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
			method.setRequestHeader("Content-Type","application/json;charset=UTF-8"); 
			System.out.println(new String(json.toJSONString().getBytes("utf-8")));
			RequestEntity se=new StringRequestEntity(json.toJSONString(),"application/json" ,"UTF-8");
	        method.setRequestEntity(se);
	        client.executeMethod(method);
			String result=method.getResponseBodyAsString();
			method.releaseConnection();
            return result;
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}
}
